<script lang="ts" setup>
import {onMounted, ref} from 'vue';
import request from "../../service/request";
import {message} from 'ant-design-vue';
import {Tool} from "@/util/tool";

const form = ref({});//查询框绑定的数据
const ebooks = ref();//表格绑定的数据
const ebook: any = ref({});//编辑的当前记录数据
const categoryIds:any = ref([]);//级联选择框绑定的数据
const level1 = ref();//级联选择options绑定的树形结构
let categorys: any;//所有分类
const loading = ref(false);//表格数据加载等待
const visible = ref<boolean>(false);//是否显示对话框
const confirmLoading = ref<boolean>(false);//确认按钮是否显示等待效果
let categoryIdsCopy: any
/**
 * 分页器配置
 */
const pagination = ref({
  current: 1,
  pageSize: 6,
  total: 0
});
/**
 * 表格绑定的columns
 */
const columns = [
  {
    title: '封面',
    dataIndex: 'cover',
    key: 'cover',
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',

  },
  {
    title: '文档数',
    dataIndex: 'docCount',
    key: 'docCount'
  },
  {
    title: '阅读数',
    dataIndex: 'viewCount',
    key: 'viewCount'
  },
  {
    title: '点赞数',
    dataIndex: 'voteCount',
    key: 'voteCount'
  },
  {
    title: 'Action',
    key: 'action',
  }
];

/**
 * 数据查询
 **/
const handleQuery = (params: any) => {
  loading.value = true
  request.get("/ebook/list", {
    params: {
      page: params.page,
      size: params.size,
      name: params.name
    }
  }).then((res) => {
    loading.value = false;
    ebooks.value = res.data.content.list;
    // 重置分页按钮
    pagination.value.current = params.page;
    pagination.value.total = res.data.content.total;
  })
};

/**
 * 表格点击页码时触发
 */
const handleTableChange = (pagination: any) => {
  handleQuery({
    page: pagination.current,
    size: pagination.pageSize
  });
};
/**
 * 编辑电子书
 * @param record
 */
const edit = (record: any) => {
  visible.value = true
  ebook.value = Tool.copy(record)
  categoryIds.value = [getCategoryName(ebook.value.category1Id), getCategoryName(ebook.value.category2Id)]
  categoryIdsCopy = Tool.copy(categoryIds.value)
};
/**
 * 添加电子书
 */
const add = () => {
  ebook.value = {}
  visible.value = true
};
/**
 * 删除电子书
 * @param id
 */
const del = (id: number) => {
  request.delete("/ebook/delete/" + id
  ).then((res) => {
    if (res.data.success) {
      handleQuery({
        page: 1,
        size: pagination.value.pageSize
      })
    }else {
      message.error(res.data.message)
    }
  })
};
/**
 * 获得所有分类
 */
const handleQueryCategory = () => {
  loading.value = true;
  request.get("/category/all").then((res) => {
    loading.value = false;
    categorys = res.data;
    level1.value = [];
    level1.value = Tool.array2Tree(categorys, 0);
  }).then(() => {
    handleQuery({
      page: 1,
      size: pagination.value.pageSize
    })
  })
};
/**
 * 由id转化名称
 * @param cid
 */
const getCategoryName = (cid: number) => {
  let result = "";
  categorys.forEach((item: any) => {
    if (item.id == cid) {
      result = item.name
    }
  })
  return result;
};
/**
 * 对话框确认事件
 */
const handleOk = () => {
  confirmLoading.value = true;
  if (categoryIdsCopy[0] == categoryIds.value[0]&&categoryIdsCopy[1] == categoryIds.value[1]) {
    categoryIds.value[0]=ebook.value.category1Id
    categoryIds.value[1]=ebook.value.category2Id
  }
  ebook.value.category1Id = categoryIds.value[0]
  ebook.value.category2Id = categoryIds.value[1]
  request.post("/ebook/save", ebook.value
  ).then((res) => {
    confirmLoading.value = false;
    const data = res.data;
    if (data.success) {
      visible.value = false;
      handleQuery({
        page: pagination.value.current,
        size: pagination.value.pageSize
      })
    } else {
      message.error(data.message)
    }
  })
};
/**
 * 初始加载
 */
onMounted(() => {
  handleQueryCategory()
});

</script>

<template>
  <a-layout>
    <a-layout-content :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }">
      <p>
        <a-form :model="form" layout="inline">
          <a-form-item>
            <a-input-search
                v-model:value="form.name"
                placeholder="输入名字"
                enter-button
                @search="handleQuery({page: 1,size: pagination.pageSize,name:form.name})"
            />
          </a-form-item>
          <a-form-item>
            <a-button type="primary" @click="add()">
              新增
            </a-button>
          </a-form-item>
        </a-form>
      </p>

      <a-table
          :columns="columns"
          :data-source="ebooks"
          :row-key="record => record.id"
          :pagination="pagination"
          :loading="loading"
          @change="handleTableChange"
      >
        <template #bodyCell="{column,record }">
          <template v-if="column.key==='cover'">
            <img v-if="record.cover" :src="record.cover" alt="avatar">
          </template>
          <template v-if="column.key==='category'">
            {{ getCategoryName(record.category1Id) }}/{{ getCategoryName(record.category2Id) }}
          </template>
          <template v-if="column.key==='action'">
            <a-space size="small">
              <router-link :to="'/admin/doc?ebookId='+record.id">
                <a-button type="primary">
                  文档管理
                </a-button>
              </router-link>
              <a-button type="primary" @click="edit(record)">
                编辑
              </a-button>
              <a-popconfirm
                  title="删除后不可恢复,确认删除吗?"
                  ok-text="确认"
                  cancel-text="取消"
                  @confirm="del(record.id)"
              >
                <a-button type="danger">
                  删除
                </a-button>
              </a-popconfirm>

            </a-space>
          </template>
        </template>

      </a-table>
    </a-layout-content>
  </a-layout>

  <a-modal
      v-model:visible="visible"
      cancelText="取消"
      okText="确定"
      title="电子书表单"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
  >
    <a-form :model="ebook" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="封面">
        <a-input v-model:value="ebook.cover"/>
      </a-form-item>
      <a-form-item label="名称">
        <a-input v-model:value="ebook.name"/>
      </a-form-item>
      <a-form-item label="分类">
        <a-cascader
            v-model:value="categoryIds"
            :field-names="{ label: 'name', value: 'id', children: 'children' }"
            :options="level1"
        />
      </a-form-item>
      <a-form-item label="描述">
        <a-input v-model:value="ebook.description" type="textarea"/>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
img {
  width: 30px;
  height: 30px;
}
</style>